Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.
此題要求確認兩個字串s及t在字串結構上是否相似,例如s="egg",t="add",因為s字串的第二個跟第三個字元為相同,t也是如此,所以成立並回傳True。反之若s="ege", t="add",則不成立。
所以可以用str的find來回傳指定字元的第一次出現時的index,逐一透過比對兩個字串相對位置回傳的index是否相同,若全部相同,則代表兩者為Isomorphic Strings。
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return [s.find(i) for i in s] == [t.find(j) for j in t]
希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。